﻿using Google.Protobuf.WellKnownTypes;
using Grpc.Core;
using Microsoft.AspNetCore.Authorization;
using TestGrpc.Auth;
using TestGrpc.Protos;
using static TestGrpc.Protos.Chart;

namespace TestGrpc.GrpcService
{
    public class ChartService:ChartBase
    {
        [PermissionAuthorize("Grpc_getoxy")]
        public override async Task GetOxy(NullParma request, IServerStreamWriter<LineXY> responseStream, ServerCallContext context)
        {
            var baseTime = DateTime.Now;
            var rd = new Random();
            int x=2;
            int y = 30;
            //模拟返回500条数据
            for(var i = 0; i < 500; i++)
            {
                if (context.CancellationToken.IsCancellationRequested)
                    return;
                x = x > 30 ? 2 : ++x;
                y = y < 3 ? 30 : --y;
                var ranx = (double)rd.Next(x-2,x+2);
                var rany = (double)rd.Next(y - 2, y + 2);
                await responseStream.WriteAsync(new LineXY() {Date = Timestamp.FromDateTimeOffset(baseTime.AddSeconds(i)),X=ranx,Y=rany });
                await Task.Delay(TimeSpan.FromMilliseconds(1000), context.CancellationToken);
            }
        }

        [AllowAnonymous]
        public override Task<TestMsg> SayHello(TestMsg request, ServerCallContext context)
        {
            return Task.FromResult(new TestMsg { Msg = "hi" });
        }

        [PermissionAuthorize("Grpc_Test")]
        public override Task<TestMsg> TestAuth(NullParma request, ServerCallContext context)
        {
            return Task.FromResult(new TestMsg { Msg = "请求成功" });
        }
    }
}
